/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model.db;

import model.db.table.Table;

/**
 * Author: Raoux Etienne
 * Student login: jc218934
 * Student number: 12448190
 * Date: Jul 31, 2010
 * Time: 9:46:32 AM
 * email: etienne.raoux@my.jcu.edu.au
 * alt email: jc218934@gmail.com
 */
public class Update {
    public static void row(Table row)
    {

        String setStr = getSetString(row);
        if (setStr == null) return;

        String whereStr = getWhereString(row);
        if (whereStr == null) return;

        Execute.execute("UPDATE "+row.getTableNames()[0]+" SET "+setStr+" WHERE "+whereStr);
    }

    private static String getSetString(Table row)
    {
        String setStr = "";
        String [] columnNames = row.getColumnNames();
        int length = columnNames.length;
        Object [] columnValues = row.getColumnValues();
        Class [] columnTypes = row.getColumnTypes();
        if (length != columnValues.length) return null;
        if (length != columnTypes.length) return null;
        if (length < 1) return null;

        setStr += columnNames[0];
        setStr += " = ";
        setStr += columnValues[0];
        for (int i =1; i<length; ++i)
        {
            setStr += ", ";
            setStr += columnNames[i];
            setStr += " = ";
            setStr += MySQLSyntax.correctSyntax(columnValues[i], columnTypes[i]);
        }
        return setStr;
    }

    private static String getWhereString(Table row)
    {
        String [] primaryKeyNames = row.getPrimaryKeyNames();
        int length = primaryKeyNames.length;
        Object [] primaryKeyValues = row.getPrimaryKeyValues();
        Class [] primaryKeyTypes = row.getPrimaryKeyTypes();
        if (length != primaryKeyValues.length) return null;
        if (length != primaryKeyTypes.length) return null;
        if (length < 1) return null;

        String whereStr = primaryKeyNames[0];
        whereStr += " = ";
        whereStr += primaryKeyValues[0];
        for (int i =1; i<length; ++i)
        {
            whereStr += " AND ";
            whereStr += primaryKeyNames[i];
            whereStr += " = ";
            whereStr += MySQLSyntax.correctSyntax(primaryKeyValues[i], primaryKeyTypes[i]);
        }
        return whereStr;
    }
}
